'use client'

import {useEffect, useRef, useState} from 'react'
import {Button, Card, Form, Input, message, Modal} from 'antd'
import {LockOutlined, SafetyCertificateOutlined, UserOutlined} from '@ant-design/icons'
import HALO from 'vanta/dist/vanta.halo.min'
import * as THREE from 'three'
import './styles.css'

const generateCaptchaText = () => {
  const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  let result = ''
  for (let i = 0; i < 6; i++) {
    result += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return result
}

const drawCaptcha = (canvas: HTMLCanvasElement, text: string) => {
  const ctx = canvas.getContext('2d')
  if (!ctx) return

  ctx.fillStyle = '#f0f2f5'
  ctx.fillRect(0, 0, canvas.width, canvas.height)

  ctx.font = 'bold 24px Arial'
  const textWidth = ctx.measureText(text).width
  const startX = (canvas.width - textWidth) / 2

  for (let i = 0; i < text.length; i++) {
    ctx.fillStyle = `hsl(${Math.random() * 360}, 70%, 50%)`
    ctx.save()
    ctx.translate(startX + i * 20, canvas.height / 2)
    ctx.rotate((Math.random() - 0.5) * 0.4)
    ctx.fillText(text[i], 0, 0)
    ctx.restore()
  }

  for (let i = 0; i < 5; i++) {
    ctx.beginPath()
    ctx.strokeStyle = `hsl(${Math.random() * 360}, 70%, 70%)`
    ctx.lineWidth = 1
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
    ctx.stroke()
  }

  for (let i = 0; i < 50; i++) {
    ctx.fillStyle = `hsl(${Math.random() * 360}, 70%, 70%)`
    ctx.beginPath()
    ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, Math.PI * 2)
    ctx.fill()
  }
}

export default function LoginPage() {
  const [loading, setLoading] = useState(false)
  const [vantaEffect, setVantaEffect] = useState<any>(null)
  const [captchaVisible, setCaptchaVisible] = useState(false)
  const [captchaText, setCaptchaText] = useState('')
  const [loginValues, setLoginValues] = useState<any>(null)
  const vantaRef = useRef(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)

  useEffect(() => {
    const token = localStorage.getItem('token')
    if (token) {
      window.location.href = '/home'
    }

    if (!vantaEffect) {
      setVantaEffect(
        HALO({
          el: vantaRef.current,
          THREE,
          mouseControls: true,
          touchControls: true,
          gyroControls: false,
          minHeight: 200.00,
          minWidth: 200.00,
          baseColor: 0xe6e6fa,
          backgroundColor: 0x9370db,
          amplitudeFactor: 1.50,
          size: 1.80,
          xOffset: 0.20,
          yOffset: 0.20
        })
      )
    }

    return () => {
      if (vantaEffect) vantaEffect.destroy()
    }
  }, [vantaEffect])

  useEffect(() => {
    if (captchaVisible && canvasRef.current) {
      const text = generateCaptchaText()
      setCaptchaText(text)
      drawCaptcha(canvasRef.current, text)
    }
  }, [captchaVisible])

  const refreshCaptcha = () => {
    if (canvasRef.current) {
      const text = generateCaptchaText()
      setCaptchaText(text)
      drawCaptcha(canvasRef.current, text)
    }
  }

  const onFinish = async (values: any) => {
    setLoading(true)
    try {
      console.log('登录信息:', values)
      await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟登录延迟
      
      setLoginValues(values)
      setCaptchaVisible(true)
    } catch (error) {
      message.error('登录失败，请检查用户名和密码')
    } finally {
      setLoading(false)
    }
  }

  const handleCaptchaSubmit = async (values: any) => {
    if (values.captcha.toLowerCase() !== captchaText.toLowerCase()) {
      message.error('验证码错误')
      refreshCaptcha()
      return
    }

    try {
      localStorage.setItem('token', 'dummy_token')
      localStorage.setItem('user', JSON.stringify({
        username: loginValues.username,
      }))

      message.success('登录成功')
      window.location.href = '/home'
    } catch (error) {
      message.error('登录失败，请重试')
    }
  }

  return (
    <div ref={vantaRef} className="login-container">
      <div style={{ width: '100%', maxWidth: '400px', padding: '0 24px', position: 'relative', zIndex: 1 }}>
        <Card className="login-card">
          <div style={{ textAlign: 'center', marginBottom: '32px' }}>
            <h1 className="login-title">OmniStock</h1>
            <p style={{ color: '#666' }}>库存管理系统</p>
          </div>

          <Form
            name="login"
            initialValues={{ remember: true }}
            onFinish={onFinish}
            size="large"
          >
            <Form.Item
              name="username"
              rules={[{ required: true, message: '请输入用户名' }]}
            >
              <Input
                prefix={<UserOutlined />}
                placeholder="用户名"
                className="login-input"
                style={{ height: '45px', borderRadius: '8px' }}
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
                className="login-input"
                style={{ height: '45px', borderRadius: '8px' }}
              />
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                className="login-button"
                style={{
                  width: '100%',
                  height: '45px',
                  borderRadius: '8px',
                  fontSize: '16px',
                }}
              >
                登录
              </Button>
            </Form.Item>

            <div style={{ textAlign: 'center', marginTop: '16px' }}>
              <a style={{ color: '#9370db' }}>忘记密码？</a>
            </div>
          </Form>
        </Card>
      </div>

      <Modal
        title="安全验证"
        open={captchaVisible}
        footer={null}
        closable={false}
        maskClosable={false}
        centered
      >
        <div style={{ marginBottom: '24px', textAlign: 'center' }}>
          <canvas
            ref={canvasRef}
            width={200}
            height={50}
            style={{ cursor: 'pointer' }}
            onClick={refreshCaptcha}
          />
          <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
            点击图片刷新验证码
          </div>
        </div>

        <Form onFinish={handleCaptchaSubmit}>
          <Form.Item
            name="captcha"
            rules={[{ required: true, message: '请输入验证码' }]}
          >
            <Input
              prefix={<SafetyCertificateOutlined />}
              placeholder="请输入验证码"
              style={{ height: '40px', borderRadius: '8px' }}
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              style={{
                width: '100%',
                height: '40px',
                borderRadius: '8px',
              }}
            >
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
} 